<template>
  <div class="amap-picker">
    <!-- 搜索框 -->
    <div class="search-container">
      <el-input
        v-model="keyword"
        placeholder="请输入地址搜索"
        class="search-input"
        clearable
        @keyup.enter="handleSearch"
        @clear="clearSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
        <template #suffix>
          <el-icon v-if="searching" class="is-loading"><Loading /></el-icon>
        </template>
      </el-input>
      
      <!-- 搜索建议列表 -->
      <transition name="suggestions">
        <div v-if="suggestions.length > 0" class="suggestions-list">
          <div
            v-for="(item, index) in suggestions"
            :key="index"
            class="suggestion-item"
            @click="selectSuggestion(item)"
          >
            <div class="suggestion-name">{{ item.name }}</div>
            <div class="suggestion-address">{{ item.address }}</div>
          </div>
        </div>
      </transition>
    </div>
    
    <!-- 交互式地图显示 -->
    <div class="map-container" v-loading="loading">
      <div v-if="!mapError" class="interactive-map-wrapper">
        <div ref="mapContainer" class="interactive-map"></div>
        <!-- 地图操作提示 -->
        <div class="map-overlay">
          <el-tag type="info" size="small">
            点击地图选择位置
          </el-tag>
        </div>
      </div>
      
      <!-- 地图加载失败时的备用界面 -->
      <div v-else class="map-fallback">
        <el-result
          icon="warning"
          title="地图加载失败"
          sub-title="无法加载交互式地图"
        >
          <template #extra>
            <el-space direction="vertical" style="width: 100%">
              <el-alert
                title="功能说明"
                type="success"
                :closable="false"
                show-icon
              >
                <template #default>
                  <p>✅ 地址搜索功能正常</p>
                  <p>✅ 坐标获取功能正常</p>
                  <p>⚠️ 地图选点功能暂时不可用</p>
                </template>
              </el-alert>
              <el-button type="primary" @click="retryLoadMap">重试加载地图</el-button>
            </el-space>
          </template>
        </el-result>
      </div>
      
      <!-- 坐标显示和手动输入 -->
      <div class="coordinate-input">
        <el-collapse v-model="showCoordinateInput">
          <el-collapse-item title="手动输入坐标" name="coordinate">
            <el-row :gutter="10">
              <el-col :span="11">
                <el-input
                  v-model="inputLng"
                  placeholder="经度"
                  @blur="handleCoordinateInput"
                >
                  <template #prepend>经度</template>
                </el-input>
              </el-col>
              <el-col :span="11">
                <el-input
                  v-model="inputLat"
                  placeholder="纬度"
                  @blur="handleCoordinateInput"
                >
                  <template #prepend>纬度</template>
                </el-input>
              </el-col>
              <el-col :span="2">
                <el-button @click="handleCoordinateInput" size="small">定位</el-button>
              </el-col>
            </el-row>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
    
    <!-- 选中结果显示 -->
    <div v-if="selectedLngLat" class="result-container">
      <el-alert
        title="已选择位置"
        type="success"
        :closable="false"
        show-icon
      >
        <template #default>
          <div class="result-content">
            <!-- 经纬度信息 -->
            <div class="coordinates-display">
              <el-tag type="primary" size="large" class="coordinate-tag">
                经度: {{ selectedLngLat.lng.toFixed(6) }}
              </el-tag>
              <el-tag type="primary" size="large" class="coordinate-tag">
                纬度: {{ selectedLngLat.lat.toFixed(6) }}
              </el-tag>
            </div>
            
            <!-- 地址信息 -->
            <div v-if="selectedAddress" class="address-display">
              <el-icon><LocationInformation /></el-icon>
              <span>{{ selectedAddress }}</span>
            </div>
            
            <!-- 操作按钮 -->
            <div class="result-actions">
              <el-button type="primary" @click="confirmSelection">
                <el-icon><Check /></el-icon>
                确认选择
              </el-button>
              <el-button @click="clearSelection">
                <el-icon><Close /></el-icon>
                清除选择
              </el-button>
              <el-button @click="copyCoordinates">
                <el-icon><CopyDocument /></el-icon>
                复制坐标
              </el-button>
            </div>
          </div>
        </template>
      </el-alert>
    </div>
    
    <!-- 操作提示 -->
    <div v-if="props.showTips && !selectedLngLat" class="tips">
      <el-alert
        title="使用说明"
        type="info"
        :closable="false"
        show-icon
      >
        <template #default>
          <div class="tip-content">
            <p>• 在搜索框中输入地址关键词</p>
            <p>• 从下拉列表中选择具体地址</p>
            <p>• 系统将自动获取该地址的经纬度坐标</p>
          </div>
        </template>
      </el-alert>
    </div>

    <!-- API Key配置说明弹窗 -->
    <el-dialog
      v-model="showApiKeyHelp"
      title="高德地图API Key配置说明"
      width="600px"
    >
      <div class="api-help-content">
        <el-steps :active="3" direction="vertical">
          <el-step title="注册高德开发者账号">
            <template #description>
              <p>访问 <a href="https://lbs.amap.com/" target="_blank">高德开放平台</a> 注册开发者账号</p>
            </template>
          </el-step>
          <el-step title="创建应用">
            <template #description>
              <p>在控制台创建新应用，选择"Web端(JS API)"</p>
            </template>
          </el-step>
          <el-step title="获取API Key">
            <template #description>
              <p>在应用管理中获取API Key</p>
            </template>
          </el-step>
          <el-step title="配置API Key">
            <template #description>
              <p>将API Key配置到 <code>src/config/amap.js</code> 文件中：</p>
              <el-input
                v-model="tempApiKey"
                placeholder="请输入你的API Key"
                style="margin: 10px 0;"
              />
              <el-button type="primary" @click="updateApiKey" :disabled="!tempApiKey">
                应用配置
              </el-button>
            </template>
          </el-step>
        </el-steps>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from "vue";
import { ElMessage } from 'element-plus';
import { Search, Loading, LocationInformation, Check, Close, CopyDocument } from '@element-plus/icons-vue';
import { AMAP_CONFIG } from "@/config/amap";
import { loadAmapJs } from "@/utils/loadAmap";
import { 
  inputTips, 
  getAddressByLocation
} from "@/api/amap";

const mapContainer = ref(null);
let map = null;
let marker = null;

const loading = ref(true);
const searching = ref(false);
const keyword = ref("");
const selectedLngLat = ref(null);
const selectedAddress = ref("");
const suggestions = ref([]);
const mapError = ref(false);
const zoom = ref(13);
const center = ref([116.397428, 39.90923]);
const inputLng = ref("");
const inputLat = ref("");
const showApiKeyHelp = ref(false);
const tempApiKey = ref("");
const showCoordinateInput = ref([]);

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => null
  },
  center: { 
    type: Array, 
    default: () => [116.397428, 39.90923] 
  },
  zoom: { 
    type: Number, 
    default: 13 
  },
  city: {
    type: String,
    default: '全国'
  },
  height: {
    type: String,
    default: '400px'
  },
  showTips: {
    type: Boolean,
    default: true
  }
});

const emit = defineEmits(['update:modelValue', 'change', 'confirm']);

// 监听外部传入的值变化
watch(() => props.modelValue, (newVal) => {
  if (newVal && newVal.lng && newVal.lat) {
    selectedLngLat.value = newVal;
    center.value = [newVal.lng, newVal.lat];
    inputLng.value = newVal.lng.toString();
    inputLat.value = newVal.lat.toString();
    
    // 更新地图位置和标记
    if (map) {
      setMarker(newVal.lng, newVal.lat);
      map.setCenter([newVal.lng, newVal.lat]);
    }
    
    getAddressByLngLat(newVal.lng, newVal.lat);
  }
}, { immediate: true });

// 初始化地图
onMounted(async () => {
  try {
    console.log('开始初始化交互式地图...');
    const AMap = await loadAmapJs(AMAP_CONFIG.apiKey);
    
    // 创建地图
    map = new AMap.Map(mapContainer.value, {
      center: props.center,
      zoom: props.zoom,
      resizeEnable: true,
    });

    // 地图加载完成事件
    map.on('complete', () => {
      console.log('地图加载完成');
      loading.value = false;
    });

    // 地图点击事件
    map.on('click', handleMapClick);

    // 如果有初始值，设置标记
    if (props.modelValue && props.modelValue.lng && props.modelValue.lat) {
      setMarker(props.modelValue.lng, props.modelValue.lat);
      getAddressByLngLat(props.modelValue.lng, props.modelValue.lat);
    }

  } catch (error) {
    console.error('地图初始化失败:', error);
    mapError.value = true;
    loading.value = false;
    ElMessage.error('地图加载失败，但搜索功能仍可正常使用');
  }
});

// 处理搜索 - 实时搜索
async function handleSearch() {
  if (!keyword.value.trim()) {
    suggestions.value = [];
    return;
  }
  
  searching.value = true;
  
  try {
    // 使用输入提示API获得更好的搜索体验
    const response = await inputTips({
      keywords: keyword.value,
      city: props.city
    });
    
    if (response.status === '1' && response.tips) {
      suggestions.value = response.tips
        .filter(tip => tip.location && tip.location !== '') // 过滤掉没有坐标的结果
        .map(tip => ({
          name: tip.name,
          address: tip.district + tip.address,
          location: tip.location.split(',').map(Number),
          district: tip.district,
          adcode: tip.adcode
        }));
    } else {
      suggestions.value = [];
    }
  } catch (error) {
    console.error('搜索失败:', error);
    suggestions.value = [];
  } finally {
    searching.value = false;
  }
}

// 监听输入变化，实时搜索
watch(keyword, (newVal) => {
  if (newVal && newVal.trim()) {
    // 防抖处理
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => {
      handleSearch();
    }, 300);
  } else {
    suggestions.value = [];
  }
});

let searchTimer = null;

// 选择搜索建议
function selectSuggestion(item) {
  const [lng, lat] = item.location;
  
  // 设置搜索框显示选中的地点名称
  keyword.value = item.name;
  
  // 设置地图标记和中心点
  if (map) {
    setMarker(lng, lat);
    map.setCenter([lng, lat]);
    map.setZoom(15); // 放大显示选中位置
  }
  
  // 更新位置信息
  updateSelection(lng, lat, item.address);
  
  // 清空建议列表
  suggestions.value = [];
  
  console.log('选中地址:', {
    name: item.name,
    address: item.address,
    coordinates: { lng, lat }
  });
}

// 处理地图点击
function handleMapClick(e) {
  const { lng, lat } = e.lnglat;
  
  console.log('地图点击位置:', { lng, lat });
  
  // 设置标记
  setMarker(lng, lat);
  
  // 清空搜索框
  keyword.value = '';
  suggestions.value = [];
  
  // 更新选中信息
  updateSelection(lng, lat);
  
  ElMessage.success('已选择地图位置');
}

// 设置或更新标记
function setMarker(lng, lat) {
  if (!map) return;
  
  const position = new window.AMap.LngLat(lng, lat);
  
  if (!marker) {
    marker = new window.AMap.Marker({
      map,
      position,
      draggable: true,
      cursor: 'move'
    });
    
    // 监听拖拽结束事件
    marker.on('dragend', handleMarkerDragEnd);
  } else {
    marker.setPosition(position);
  }
}

// 处理标记拖拽结束
function handleMarkerDragEnd(e) {
  const pos = e.target.getPosition();
  const { lng, lat } = pos;
  
  console.log('标记拖拽到:', { lng, lat });
  
  // 更新选中信息
  updateSelection(lng, lat);
  
  ElMessage.success('标记位置已更新');
}

// 处理坐标输入
function handleCoordinateInput() {
  const lng = parseFloat(inputLng.value);
  const lat = parseFloat(inputLat.value);
  
  if (isNaN(lng) || isNaN(lat)) {
    ElMessage.warning('请输入有效的经纬度');
    return;
  }
  
  if (lng < -180 || lng > 180 || lat < -90 || lat > 90) {
    ElMessage.warning('经纬度范围不正确');
    return;
  }
  
  // 设置地图标记和中心点
  if (map) {
    setMarker(lng, lat);
    map.setCenter([lng, lat]);
    map.setZoom(15);
  }
  
  updateSelection(lng, lat);
}

// 根据经纬度获取地址
async function getAddressByLngLat(lng, lat) {
  try {
    const response = await getAddressByLocation(lng, lat);
    if (response.status === '1' && response.regeocode) {
      selectedAddress.value = response.regeocode.formatted_address;
    }
  } catch (error) {
    console.error('获取地址失败:', error);
  }
}

// 重试加载地图
function retryLoadMap() {
  mapError.value = false;
  loading.value = true;
  
  // 重新初始化地图
  setTimeout(async () => {
    try {
      const AMap = await loadAmapJs(AMAP_CONFIG.apiKey);
      
      // 重新创建地图
      if (mapContainer.value) {
        map = new AMap.Map(mapContainer.value, {
          center: center.value,
          zoom: zoom.value,
          resizeEnable: true,
        });

        map.on('complete', () => {
          loading.value = false;
          mapError.value = false;
        });

        map.on('click', handleMapClick);

        // 如果有选中位置，重新设置标记
        if (selectedLngLat.value) {
          setMarker(selectedLngLat.value.lng, selectedLngLat.value.lat);
        }
      }
    } catch (error) {
      console.error('重试加载地图失败:', error);
      mapError.value = true;
      loading.value = false;
    }
  }, 1000);
}

// 更新选中信息
function updateSelection(lng, lat, address = '') {
  const lngLatObj = { lng, lat };
  selectedLngLat.value = lngLatObj;
  center.value = [lng, lat];
  inputLng.value = lng.toString();
  inputLat.value = lat.toString();
  
  if (address) {
    selectedAddress.value = address;
  } else {
    // 获取地址信息
    getAddressByLngLat(lng, lat);
  }
  
  // 触发事件
  emit('update:modelValue', lngLatObj);
  emit('change', {
    lngLat: lngLatObj,
    address: selectedAddress.value
  });
}

// 确认选择
function confirmSelection() {
  if (!selectedLngLat.value) {
    ElMessage.warning('请先选择一个位置');
    return;
  }
  
  emit('confirm', {
    lngLat: selectedLngLat.value,
    address: selectedAddress.value
  });
  
  ElMessage.success('位置选择成功');
}

// 清除选择
function clearSelection() {
  selectedLngLat.value = null;
  selectedAddress.value = '';
  inputLng.value = '';
  inputLat.value = '';
  keyword.value = '';
  suggestions.value = [];
  center.value = props.center;
  
  // 清除地图标记
  if (marker) {
    marker.setMap(null);
    marker = null;
  }
  
  // 重置地图中心
  if (map) {
    map.setCenter(props.center);
    map.setZoom(props.zoom);
  }
  
  emit('update:modelValue', null);
  emit('change', null);
}

// 清除搜索
function clearSearch() {
  keyword.value = '';
  suggestions.value = [];
}

// 点击外部区域关闭搜索建议
function handleClickOutside(event) {
  const searchContainer = document.querySelector('.search-container');
  if (searchContainer && !searchContainer.contains(event.target)) {
    suggestions.value = [];
  }
}

// 监听点击外部事件
onMounted(() => {
  document.addEventListener('click', handleClickOutside);
});

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside);
});

// 复制坐标
function copyCoordinates() {
  if (!selectedLngLat.value) return;
  
  const coordinates = `${selectedLngLat.value.lng},${selectedLngLat.value.lat}`;
  navigator.clipboard.writeText(coordinates).then(() => {
    ElMessage.success('坐标已复制到剪贴板');
  }).catch(() => {
    // 备用方案
    const textArea = document.createElement('textarea');
    textArea.value = coordinates;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand('copy');
    document.body.removeChild(textArea);
    ElMessage.success('坐标已复制到剪贴板');
  });
}

// 更新API Key（这里只是演示，实际项目中需要重新构建）
function updateApiKey() {
  if (!tempApiKey.value) {
    ElMessage.warning('请输入有效的API Key');
    return;
  }
  
  ElMessage.info('请将API Key更新到 src/config/amap.js 文件中，然后重新构建项目');
  showApiKeyHelp.value = false;
}

// 组件销毁时清理
onBeforeUnmount(() => {
  // 清理地图资源
  if (map) {
    map.destroy();
    map = null;
  }
  marker = null;
  
  // 清理定时器
  if (searchTimer) {
    clearTimeout(searchTimer);
    searchTimer = null;
  }
  
  // 清理事件监听
  document.removeEventListener('click', handleClickOutside);
  
  suggestions.value = [];
});

// 暴露方法给父组件
defineExpose({
  setPosition: (lng, lat) => {
    if (map) {
      setMarker(lng, lat);
      map.setCenter([lng, lat]);
    }
    updateSelection(lng, lat);
  },
  clearPosition: clearSelection,
  getMap: () => map
});
</script>

<style scoped>
.amap-picker {
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.search-container {
  padding: 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  position: relative;
  z-index: 10000;
}

.search-input {
  width: 100%;
}

.map-container {
  width: 100%;
  min-height: 300px;
  position: relative;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.interactive-map-wrapper {
  position: relative;
  width: 100%;
  height: v-bind(height);
  min-height: 400px;
  z-index: 1;
}

.interactive-map {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.map-overlay {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
  pointer-events: none;
}

.coordinate-input {
  padding: 12px;
  background: #f8f9fa;
  border-top: 1px solid #e9ecef;
}

.suggestions-list {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: #fff;
  border: 1px solid #dcdfe6;
  border-top: none;
  border-radius: 0 0 4px 4px;
  max-height: 200px;
  overflow-y: auto;
  z-index: 99999;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
}

.suggestion-item {
  padding: 12px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.suggestion-item:hover {
  background-color: #f5f7fa;
}

.suggestion-item:last-child {
  border-bottom: none;
}

.suggestion-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.suggestion-address {
  font-size: 12px;
  color: #909399;
}

/* 搜索建议过渡动画 */
.suggestions-enter-active,
.suggestions-leave-active {
  transition: all 0.2s ease;
}

.suggestions-enter-from,
.suggestions-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

.suggestions-enter-to,
.suggestions-leave-from {
  opacity: 1;
  transform: translateY(0);
}

.map-fallback {
  padding: 40px 20px;
  background: #fafafa;
  border-radius: 4px;
  text-align: center;
}

.map-fallback .el-result {
  padding: 20px 0;
}

.map-fallback .el-alert p {
  margin: 4px 0;
  text-align: left;
}

.map-placeholder {
  padding: 60px 20px;
  background: #fafafa;
  border-radius: 4px;
  text-align: center;
}

.result-container {
  margin-top: 16px;
}

.result-content {
  margin-top: 12px;
}

.coordinates-display {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.coordinate-tag {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  padding: 8px 12px;
  font-weight: 600;
}

.address-display {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding: 8px 12px;
  background: rgba(64, 158, 255, 0.1);
  border-radius: 4px;
  color: #409eff;
  font-size: 14px;
}

.result-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.result-actions .el-button {
  display: flex;
  align-items: center;
  gap: 4px;
}

.tips {
  padding: 16px;
  background: #f8f9fa;
}

.tip-content {
  margin: 0;
}

.tip-content p {
  margin: 4px 0;
  font-size: 13px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .amap-picker {
    margin: 0;
    border-radius: 0;
  }
  
  .search-container,
  .result-container,
  .tips {
    padding: 12px;
  }
  
  .map-container {
    height: 300px;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .info-item .label {
    margin-bottom: 4px;
  }
  
  .result-actions {
    flex-direction: column;
  }
  
  .result-actions .el-button {
    width: 100%;
  }
}

/* 隐藏提示 */
.amap-picker.hide-tips .tips {
  display: none;
}

/* 加载状态 */
.map-container .el-loading-mask {
  border-radius: 0;
}

/* 高德地图控件样式调整 */
:deep(.amap-logo) {
  opacity: 0.6;
}

:deep(.amap-copyright) {
  opacity: 0.6;
}

/* 搜索框样式 */
.search-input :deep(.el-input__wrapper) {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border: 1px solid #dcdfe6;
}

.search-input :deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc;
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

/* API帮助内容样式 */
.api-help-content {
  :deep(.el-step__description) p {
    margin: 8px 0;
    line-height: 1.6;
  }
  
  :deep(.el-step__description) a {
    color: #409eff;
    text-decoration: none;
  }
  
  :deep(.el-step__description) a:hover {
    text-decoration: underline;
  }
  
  :deep(.el-step__description) code {
    background: #f5f5f5;
    padding: 2px 6px;
    border-radius: 3px;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 13px;
  }
}
</style>
